<template>
    <el-card shadow="never" class="border-0">
        <!-- 搜索 -->
        <el-form :model="searchForm" label-width="80px" class="mb-3" size="small">
            <el-row :gutter="20">
                <el-col :span="5" :offset="0">
                    <el-form-item label="真实姓名">
                        <el-input v-model="searchForm.realName" placeholder="真实姓名" clearable></el-input>
                    </el-form-item>
                </el-col>

                <el-col :span="5">
                    <el-form-item label="手机号">
                        <el-input v-model="searchForm.phone" placeholder="手机号" clearable></el-input>
                    </el-form-item>
                </el-col>

                <el-col :span="5">
                    <el-form-item label="绑定状态">
                        <el-select v-model="searchForm.isBind" filterable placeholder="请选择绑定状态" clearable>
                            <el-option key="0" label="未绑定" value="0" />
                            <el-option key="1" label="已绑定" value="1" />
                        </el-select>
                    </el-form-item>
                </el-col>

                <el-col :span="5">
                    <div class="flex items-center justify-end">
                        <el-button type="primary" @click="getData(1)">搜索</el-button>
                        <el-button @click="clickResetBtn">重置</el-button>
                    </div>
                </el-col>
            </el-row>
        </el-form>

        <!-- 新增|刷新 -->
        <div class="flex items-center  mb-4">
            <el-button type="primary" size="small" @click="clickAddBtn(0)">新增</el-button>
        </div>

        <!-- 表格数据 -->
        <el-table :data="tableData" stripe style="width: 100%" v-loading="tableDataLoading">

            <el-table-column prop="realName" label="真实姓名" align="center"></el-table-column>

            <!-- <el-table-column prop="roleType" label="角色类型" align="center">
                <template #default="{ row }">
                {{ transferWxUserType(row.roleType) }}
                </template>
</el-table-column> -->

            <el-table-column prop="deptName" label="部门名称" align="center"></el-table-column>

            <el-table-column prop="phone" label="手机号" #default="{ row }" align="center">
                {{ row.phone }}
            </el-table-column>

            <!-- <el-table-column prop="idCard" label="身份证" #default="{ row }" align="center">
                {{ row.idCard }}
            </el-table-column> -->

            <el-table-column prop="email" label="邮箱" align="center" width="230px"></el-table-column>

            <el-table-column prop="sex" label="性别" align="center" width="80px">
                <template #default="{ row }">
                    {{ transferSex(row.sex) }}
                </template>
            </el-table-column>

            <el-table-column prop="isBind" label="绑定状态" align="center">
                <template #default="{ row }">
                    {{ transferWxUserBind(row.isBind) }}
                </template>
            </el-table-column>

            <el-table-column label="绑定时间" align="center">
                <template #default="{ row }">
                    {{ dateFormatter(row.bindTime) }}
                </template>
            </el-table-column>

            <!-- <el-table-column prop="wechatNick" label="微信昵称" align="center"></el-table-column> -->

            <!-- <el-table-column prop="address" label="详细地址" show-overflow-tooltip></el-table-column> -->
            <el-table-column prop="remark" label="备注信息" align="center" show-overflow-tooltip></el-table-column>

            <el-table-column prop="state" label="状态" align="center" width="100px">
                <template #default="{ row }">
                    {{ transferWxUserState(row.status) }}
                </template>
            </el-table-column>

            <!-- <el-table-column prop="createPersonName" label="创建人" align="center">
                <template #default="{ row }">
                {{ row.createPersonName }}
                </template>
            </el-table-column> -->

            <el-table-column label="创建时间" align="center">
                <template #default="{ row }">
                    {{ dateFormatter(row.createTime) }}
                </template>
            </el-table-column>

            <el-table-column label="操作" align="center" fixed="right" width="240">
                <template #default="scope">
                    <div>
                        <!-- <el-popconfirm title="是否要审核通过该工程师？" confirmButtonText="确认" cancelButtonText="取消"
                            @confirm="chageUserStatus(scope.row.id, 1)">
                            <template #reference>
                                <el-button v-if="scope.row.status == 2" type="primary" size="small" text>审核</el-button>
                            </template>
    </el-popconfirm> -->

                        <!-- <el-popconfirm title="是否要挂起该工程师？" confirmButtonText="确认" cancelButtonText="取消"
                            @confirm="chageUserStatus(scope.row.id, 2)">
                            <template #reference>
                                <el-button v-if="scope.row.status == 1" type="primary" size="small" text>挂起</el-button>
                            </template>
                        </el-popconfirm> -->

                        <el-button v-if="scope.row.status == 2" type="primary" size="small" text
                            @click="showAuditWin(scope.row)">审核</el-button>

                        <el-button v-if="scope.row.status != 2" type="primary" size="small" text
                            @click="clickEditBtn(scope.row)">修改</el-button>

                        <el-popconfirm title="是否要初始化密码？" confirmButtonText="确认" cancelButtonText="取消"
                            @confirm="initPwd(scope.row.id)">
                            <template #reference>
                                <el-button text type="primary" size="small">重置密码</el-button>
                            </template>
                        </el-popconfirm>

                        <el-popconfirm v-if="scope.row.status != 2" title="是否要删除该工程师？" confirmButtonText="确认"
                            cancelButtonText="取消" @confirm="clickDeleteBtn(scope.row.id)">
                            <template #reference>
                                <el-button text type="primary" size="small">删除</el-button>
                            </template>
                        </el-popconfirm>
                    </div>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页组件 -->
        <div class="flex items-center justify-center mt-5">
            <el-pagination background layout="prev, pager ,next" :total="total" :current-page="currentPage"
                :page-size="limit" @current-change="getData" />
        </div>

        <!-- 新增 更新 抽屉 -->
        <FormDrawer ref="formDrawerRef" :title="drawerTitle" @submit="clickDrawerSubmitBtn" size="40%">
            <el-form :model="form" ref="formRef" :rules="rules" label-width="120px" :inline="false">

                <el-form-item required label="真实姓名" prop="realName">
                    <el-input v-model="form.realName" placeholder="真实姓名"></el-input>
                </el-form-item>

                <el-form-item required label="手机号" prop="phone">
                    <el-input v-model="form.phone" placeholder="手机号"></el-input>
                </el-form-item>

                <!-- <el-form-item label="身份证" prop="idCard">
                    <el-input v-model="form.idCard" ></el-input>
                </el-form-item> -->

                <el-form-item label="部门" prop="deptId">
                    <el-cascader required v-model="form.deptId" ref="dept_el_cascader_ref"
                        @change="handleChange_department" :props="departmentTreeProp" :options="departmentTreeData"
                        :show-all-levels="false" popper-class="popper" />
                </el-form-item>

                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="form.email" placeholder="邮箱"></el-input>
                </el-form-item>

                <el-form-item label="性别" prop="sex">
                    <el-switch v-model="form.sex" active-text="女" active-value="2" inactive-text="男"
                        inactive-value="1" />
                </el-form-item>

                <!-- <el-form-item label="详细地址" prop="address">
                    <el-input v-model="form.address" ></el-input>
                </el-form-item> -->

                <el-form-item label="备注" prop="remark">
                    <el-input type="textarea" v-model="form.remark" placeholder="备注"></el-input>
                </el-form-item>

                <el-form-item label="个人照片" prop="avatar">
                    <el-upload
                        class="avatar-uploader"
                        action="#"
                        :show-file-list="false"
                        :before-upload="beforeAvatarUpload"
                        :http-request="handleAvatarUpload"
                        accept="image/*">
                        <img v-if="form.avatar" :src="form.avatar" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                    </el-upload>
                </el-form-item>

            </el-form>
        </FormDrawer>
    </el-card>


    <!-- 审核 -->
    <SystemDialog title="注册工程师账号审核" :visible="showAuditDialogVisible" :height="40" :width="30" :showCloseBtn="true"
        :showOkBtn="true" okBtnName="确认" @on-close="showAuditDialogVisible = false" @on-confirm="submitAudit()">
        <template v-slot:content>
            <div style="padding: 20px;">
                <el-form label-width="150px" :inline="false">
                    <el-form-item label="国籍：">
                        <span>{{ auditRow.nationality }}</span>
                    </el-form-item>
                    <el-form-item label="用户名：">
                        <span>{{ auditRow.username }}</span>
                    </el-form-item>
                    <el-form-item label="真实姓名：">
                        <span>{{ auditRow.realName }}</span>
                    </el-form-item>
                    <el-form-item label="电话：" v-if="null != auditRow.nationality && auditRow.nationality == '中国'">
                        <span>{{ auditRow.phone }}</span>
                    </el-form-item>
                    <el-form-item label="邮箱：" v-else>
                        <span>{{ auditRow.email }}</span>
                    </el-form-item>
                </el-form>
                <el-form :model="auditForm" ref="auditFormRef" :rules="auditFormRules" label-width="150px"
                    :inline="false">
                    <el-form-item label="审批结果">
                        <el-select v-model="auditForm.status">
                            <el-option label="同意" value=1></el-option>
                            <el-option label="拒绝" value=2></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="审批意见" prop="remark" v-if="auditForm.status == 2">
                        <el-input type="textarea" :rows="2" v-model="auditForm.remark" placeholder="审批意见"></el-input>
                    </el-form-item>
                </el-form>
            </div>
        </template>
    </SystemDialog>

    <el-dialog v-model="resetpasswordDialogVisible" title="重置密码结果" width="500" align-center>
        <text>{{ resetpasswordDialogResult }}</text>
        <template #footer>
            <div class="dialog-footer">
                <el-button type="primary" @click="resetpasswordDialogVisible = false">
                    关闭
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup>

import { ref, onMounted, reactive, computed } from 'vue'
import SystemDialog from "~/components/SystemDialog.vue";
import { api_department_tree } from "~/api/departmentApi";
import { api_user_list, api_user_add, api_user_update, api_user_delete, api_user_audit,api_avatar_uploadFile } from "~/api/userApi";
import { updateManagerStatus,resetpassword } from "~/api/manager"
import { api_ship_uploadFile } from "~/api/supply"
import FormDrawer from '~/components/FormDrawer.vue'
import { toast, toastWarn } from "~/composables/util"
import { useStore } from 'vuex'
import { transferSex, transferWxUserBind, dateFormatter, transferWxUserState } from '~/utils/common.js'
import { checkPhone, checkEmail } from '~/utils/validate.js'

//审核弹窗
const showAuditDialogVisible = ref(false)

const resetpasswordDialogVisible = ref(false)
const resetpasswordDialogResult = ref('')

// 页面变量
const store = useStore()
const tableData = ref([]) // 列表数据
const currentPage = ref(1)
const total = ref(0)
const limit = ref(10)
const tableDataLoading = ref(false)
const rules = {
    realName: [
        { required: true, message: '真实姓名不能为空', trigger: 'change' }
    ],
    phone: [
        { validator: checkPhone, required: true, trigger: 'change' }
    ],
    deptId: [
        { required: true, message: '部门信息不能为空', trigger: 'change' }
    ],
    email: [
        { validator: checkEmail, required: true, trigger: 'change' }
    ],
}
const editId = ref(0)
const drawerTitle = computed(() => editId.value ? "修改" : "新增")
const searchForm = reactive({
    //1开发管理员 2超级管理员 3普通管理员 4工程师用户 5客户公司负责人
    roleId: 4,
    realName: "",
    phone: "",
    isBind: "",
    page: currentPage.value,
    size: limit.value,
})
const form = reactive({
    id: editId.value,
    realName: "",
    phone: "",
    //1开发管理员 2超级管理员 3普通管理员 4工程师用户 5客户公司负责人
    roleId: 4,
    deptId: null,
    email: "",
    sex: "1",
    address: "",
    remark: "",
    idCard: "",
    avatar: ""
})
const formRef = ref(null)
const formDrawerRef = ref(null)
const dept_el_cascader_ref = ref(null)
const departmentTreeData = ref([])

//props
const departmentTreeProp = {
    label: 'name',
    value: 'id',
    checkStrictly: true,
    emitPath: false
}

// 生命周期
onMounted(() => {
    //加载部门字典信息
    getDepartmentTreeData()
    //加载表格数据
    getData()

})

//获取列表数据
function getData(p = null) {
    if (typeof p == "number") {
        currentPage.value = p
    }

    tableDataLoading.value = true
    searchForm.page = currentPage.value
    api_user_list(searchForm)
        .then(res => {
            if (res) {
                tableData.value = res.records
                total.value = res.total
            } else {
                tableData.value = []
                total.value = 0
            }
        })
        .finally(() => {
            tableDataLoading.value = false
        })
}

// 获取部门tree
function getDepartmentTreeData() {
    api_department_tree()
        .then(res => {
            departmentTreeData.value = res
        })
}

//点击重置按钮
const clickResetBtn = () => {
    searchForm.realName = ""
    searchForm.phone = ""
    searchForm.isBind = ""
    getData(1)
}


// 重置表单
function resetForm(row = false) {
    if (formRef.value) formRef.value.resetFields()
    if (row) {
        for (const key in form) {
            form[key] = row[key]
        }
    }
}

// 点击新增角色抽屉中 提交按钮
const clickDrawerSubmitBtn = () => {
    formRef.value.validate((valid) => {
        if (!valid) return
        console.log('form', form)
        formDrawerRef.value.showLoading()

        const fun = editId.value ? api_user_update(editId.value, form) : api_user_add(form)

        fun.then(res => {
            toast(drawerTitle.value + "成功")
            // 修改刷新当前页，新增刷新第一页
            getData(editId.value ? false : 1)
            formDrawerRef.value.close()
        }).catch(err => {

        }).finally(() => {
            formDrawerRef.value.hideLoading()
        })

    })
}

// 编辑
const clickEditBtn = (row) => {
    editId.value = row.id
    resetForm(row)

    formDrawerRef.value.open()
}

// 新增
const clickAddBtn = () => {
    //修改标记置为0
    editId.value = 0
    resetForm({
        realName: "",
        phone: "",
        //1开发管理员 2超级管理员 3普通管理员 4工程师用户 5客户公司负责人
        roleId: 4,
        deptId: null,
        email: "",
        sex: "1",
        address: "",
        remark: "",
        idCard: "",
        avatar: ""
    })
    formDrawerRef.value.open()
}

// 获取|挂起用户
const chageUserStatus = (id, status) => {
    tableDataLoading.value = true
    updateManagerStatus(id, status).then(res => {
        if (status == "1") {
            toast("恢复成功")
        } else {
            toast("挂起成功")
        }
        getData()
    })
        .finally(() => {
            tableDataLoading.value = false
        })
}

// 删除
const clickDeleteBtn = (id) => {
    tableDataLoading.value = true
    api_user_delete(id).then(res => {
        toast("删除成功")
        getData()
    }).catch(err => {

    }).finally(() => {
        tableDataLoading.value = false
    })
}

// 获取省市区
const handleGetAdress = (data) => {
    console.log('省市区： ', data)
    form['province'] = data.code[0]
    form['city'] = data.code[1]
    console.log('province: ', formRef.value.province)
}

// 选择部门
const handleChange_department = (data) => {
    let checkedNode = dept_el_cascader_ref.value.getCheckedNodes()?.[0]
    // formRef.value.deptId = checkedNode.value
    form['deptName'] = checkedNode.label
}

// 当前审核数据row
const auditRow = ref(null)

// 审核表单
const auditFormRef = ref(null)

// 审批结果
const auditForm = reactive({
    id: null,
    status: "1",
    remark: null
})

// 审批结果表单校验
const auditFormRules = {
    remark: [
        { required: true, message: '审批意见不能为空', trigger: 'change' }
    ]
}

// 打开审核弹窗
const showAuditWin = (row) => {
    auditRow.value = row
    //置空数据
    auditForm.id = row.id
    auditForm.status = "1"
    auditForm.remark = null
    showAuditDialogVisible.value = true
}

// 提交审核结果
const submitAudit = () => {
    //表单校验
    auditFormRef.value.validate((valid) => {
        if (!valid) return
        //请求接口
        api_user_audit(auditForm).then(res => {
            toast("操作成功")
            getData()
        }).finally(() => {
            showAuditDialogVisible.value = false
        })
    }).finally(() => {
    })
}

// 修改状态
const initPwd = (userId) => {
    resetpassword(userId).then((res) => {
        resetpasswordDialogVisible.value = true
        resetpasswordDialogResult.value = res
    })
}

// 头像上传相关函数
const beforeAvatarUpload = (file) => {
    const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
    const isLt2M = file.size / 1024 / 1024 < 2

    if (!isJPG) {
        toastWarn('上传头像图片只能是 JPG/PNG 格式!')
    }
    if (!isLt2M) {
        toastWarn('上传头像图片大小不能超过 2MB!')
    }
    return isJPG && isLt2M
}

const handleAvatarUpload = (param) => {
    const file = param.file
    const formData = new FormData()
    formData.append('file', file)
    // 调用后端上传API
    api_avatar_uploadFile(formData).then((res) => {
        if (res && res.length > 0) {
            console.log('res', res)
            form.avatar = res[0].url // 假设后端返回的是图片URL数组
            toast('头像上传成功')
        } else {
            toastWarn('头像上传失败')
        }
    }).catch((error) => {
        console.error('上传失败:', error)
        toastWarn('头像上传失败，请重试')
    })
}
</script>

<style>
.popper .el-cascader-panel .el-radio {
    width: 100%;
    height: 100%;
    z-index: 10;
    position: absolute;
    top: 0px !important;
    right: 0px !important;
}

.popper .el-cascader-panel .el-checkbox {
    width: 100%;
    height: 100%;
    z-index: 10;
    position: absolute;
    top: 0px;
    right: 0px;
}

.popper .el-cascader-panel .el-radio__input {
    margin-left: 8px;
}

.popper .el-cascader-panel .el-checkbox__input {
    margin-top: 2px;
    margin-left: 8px;
}

.popper .el-cascader-panel .el-cascader-node__postfix {
    top: 10px;
}

.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 120px;
    text-align: center;
    line-height: 120px;
}

.avatar {
    width: 100px;
    height: 120px;
    display: block;
    object-fit: cover;
}
</style>